package cn.hpclub.server.model;

import java.util.Date;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.jfinal.ext.plugin.tablebind.TableBind;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Model;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;

import cn.hpclub.server.constant.Constant;
import cn.hpclub.server.service.SalePromotionService;
import cn.hpclub.server.util.DateKit;
import cn.hpclub.server.util.InterfaceUtil;

@TableBind(tableName = "sales_promotion")
public class SalePromotion extends Model<SalePromotion>{
    private static final Logger       logger          = LoggerFactory.getLogger(SalePromotion.class);
    public static final SalePromotion dao             = new SalePromotion();
    public static int                 REWARD_ALL      = 100;

    public static String              ID              = "id";                                        // 数据库id
    public static String              USERID          = "userid";                                    // 用户id
    public static String              AMOUNT          = "amount";                                    // 金额
    public static String              MODULEID        = "moduleId";                                  // 模块id
    public static String              REWARD          = "reward";                                    // 酬金
    public static String              TIME            = "time";                                      // 时间
    public static String              APPID           = "appid";                                     //
    public static String              ORDER_ID        = "order_id";                                  // 订单号
    public static String              PHONE_NO        = "phone_no";
    public static String              STOREID         = "storeid";                                   // 机构id
    public static String              RETURN_CODE     = "return_code";                               // 回调状态
    public static String              RETURN_MSG      = "return_msg";                                // 回调信息
    public static String              ORG_ID          = "org_id";                                    // 机构id
    public static String              BUSINESS_CODE   = "business_code";                             // 资费代码
    public static String              SYSTEMID        = "systemid";                                  // 系统id
    public static String              SOURCE          = "source";                                    // 分销平台
    public static String              METHOD          = "method";                                    // 接口
    public static String              SALETYPE        = "saletype";                                  // 购买方式

    public static String              IS_USED         = "is_used";
    public static String              USED_TIME       = "used_time";
    public static String              WIN_TYPE        = "winning_type";
    public static String              WIN_NAME        = "winning_name";
    public static String              INTE_RES_CODE   = "inte_res_code";
    public static String              INTE_RES_MSG    = "inte_res_msg";
    public static String              FXSTR           = "fxstr";
    public static String              XMLDATA         = "xmlData";
    public static String              ISDELETE        = "isDelete";
    public static String              ISFIXDATA       = "isFixData";
    public static String              MODULECODE      = "moduleCode";
    public static String              THIRDPART_ID    = "thirdpart_id";
    public static String              FOREIGN_CONTENT = "foreign_content";
    public static String              BUSINESS_NAME   = "business_name";                             // 资费（业务）名称

    public Page<Record> query(int userid, int num, int size){
        return Db.paginate(num, size,
                           "select " + AMOUNT + "," + MODULEID + "," + REWARD
                                   + ", date_format(time, '%Y年%m月') as fmttime ",
                           " from " + Constant.Table.SALE_PROMOTION + " where " + USERID
                                   + "=? group by date_format(time, '%Y-%m') order by time desc ",
                           new Object[] { userid });

    }

    public List<SalePromotion> query(int userid, String time){
        // return find("select " + AMOUNT + "," + MODULEID + "," + REWARD + ","
        // + TIME + " from "
        // + Constant.Table.SALE_PROMOTION + " where " + USERID + "=? and
        // date_format(" + TIME + ",'%Y-%m')<=?",
        // new Object[] { userid, "" + time + "" });
        return find("select " + AMOUNT + "," + MODULEID + "," + REWARD + "," + TIME + " from "
                + Constant.Table.SALE_PROMOTION + " where return_code='0' and " + USERID + "=? and date_format(" + TIME
                + ",'%Y-%m')='" + time + "'", new Object[] { userid });
    }

    public List<Record> findReward(int userid, String businessCode, int orgId, int muduleid){
        StringBuffer sql = new StringBuffer("SELECT reward.first_remuneration,reward.normal_remuneration,");
        sql.append("(select COALESCE(sum(sales_promotion.reward),0) from sales_promotion where return_code='0' and userid=? and date_format(time,'%Y-%m')=date_format(now(),'%Y-%m')) as sum,");
        sql.append("(select COALESCE(sum(sales_promotion.reward),0) from sales_promotion where return_code='0' and userid=? and moduleid=? and date_format(time,'%Y-%m')=date_format(now(),'%Y-%m')) as sumModule,");
        sql.append("(select count(*) from sales_promotion where return_code='0' and moduleid=? and userid=? and date_format(time,'%Y-%m')=date_format(now(),'%Y-%m'))  as count ");
        sql.append("FROM reward,business ");
        sql.append("where businessCode=? and reward.business_id=business.id ");
        sql.append("and reward.org_id in ");
        sql.append(InterfaceUtil.getParentOrgIdSql(orgId, 4));

        return Db.find(sql.toString(), new Object[] { userid, userid, muduleid, muduleid, userid, businessCode });
    }

    public List<Record> findClerkReward(int muduleid, int orgId){
        StringBuffer sql = new StringBuffer("select moduleid,single_cap from cmcc_clerkreward_config ");
        sql.append("where moduleid in (?," + REWARD_ALL + ") ");
        sql.append("and enable!=0 and orgid in ");
        sql.append(InterfaceUtil.getParentOrgIdSql(orgId, 4));

        return Db.find(sql.toString(), new Object[] { muduleid });
    }

    /**
     * @param message
     * @param rechargeResult
     * @param isSuccess
     * @param cmccId
     * @param orderId
     * @return
     * @Title: saveRechargeOrder
     * @Description:TODO void
     */
    public boolean saveRechargeOrder(String orderId, String cmccId, boolean isSuccess, String rechargeResult,
            String message){
        RechargeOrder rechargeOrder = RechargeOrder.dao.getRechargeOrderByOrderId(orderId);
        if(rechargeOrder == null){
            logger.error("orderId is not exist:" + orderId);
            return false;
        }
        String returnCode = isSuccess ? "0" : "1";
        SalePromotion sale = new SalePromotion();
        sale.set(SalePromotion.APPID, Constant.APPID);
        sale.set(SalePromotion.THIRDPART_ID, rechargeOrder.getStr(RechargeOrder.ORDER_ID));
        sale.set(SalePromotion.ORDER_ID, cmccId);// 订单表中订单ID，和充值页面上的一致，充值失败则创建一个随机订单号
        sale.set(SalePromotion.AMOUNT, rechargeOrder.getDouble(RechargeOrder.RECHARGE_MONEY) * 100);// recharge表中的充值金额是以元为单位，而sales_promotion表中是以分为单位，所以需要*100进行转换
        sale.set(SalePromotion.PHONE_NO, rechargeOrder.getStr(RechargeOrder.RECHARGE_PHONE));// 充值的手机号
        sale.set(SalePromotion.TIME, DateKit.toStr(new Date(), "yyyy-MM-dd HH:mm:ss"));// 以前由调用回调函数时传入，现在new一个
        sale.set(SalePromotion.IS_USED, 0);
        sale.set(SalePromotion.USED_TIME, null);
        sale.set(SalePromotion.WIN_TYPE, null);
        sale.set(SalePromotion.WIN_NAME, null);
        sale.set(SalePromotion.ORG_ID, MemberOrg.dao.getOrgIdById(rechargeOrder.getInt(RechargeOrder.USER_ID)));// 根据userId从人员表获取，即，是人员当前所在的机构ID，而不是订单里面保存的快照orgId
        sale.set(SalePromotion.USERID, rechargeOrder.getInt(RechargeOrder.USER_ID));
        sale.set(SalePromotion.BUSINESS_CODE, Constant.RECHARGE_BUSINESS_CODE);// 以前由调用回调函数时传入，现在写死
        sale.set(SalePromotion.SYSTEMID, 0);
        sale.set(SalePromotion.SOURCE, 0);
        sale.set(SalePromotion.METHOD, null);
        sale.set(SalePromotion.RETURN_CODE, returnCode);// 以前由调用回调函数时传入，现在根据中转服务的充值接口返回值判断封装
        sale.set(SalePromotion.RETURN_MSG, message);// 以前由调用回调函数时传入，现在根据中转服务的充值接口返回
        sale.set(SalePromotion.SALETYPE, rechargeOrder.getInt(RechargeOrder.SALE_TYPE));
        sale.set(SalePromotion.INTE_RES_CODE, null);
        sale.set(SalePromotion.INTE_RES_MSG, null);
        sale.set(SalePromotion.FXSTR, null);// 以前由调用回调函数时传入，现在没有该参数了
        sale.set(SalePromotion.XMLDATA, rechargeResult);// 以前保存的回调回来的XML结构的数据，现在保存调用充值接口后的结果数据（JSON结构）
        sale.set(SalePromotion.ISDELETE, 0);
        sale.set(SalePromotion.ISFIXDATA, 0);
        sale.set(SalePromotion.MODULEID, Constant.ModuleID.JIAOFEI);// 以前由调用回调函数时传入，现在写死
        sale.set(SalePromotion.MODULECODE, Constant.RECHARGE_MODULECODE);// 以前由调用回调函数时传入，现在写死
        sale.set(SalePromotion.BUSINESS_NAME, Constant.RECHARGE_BUSINESS_NAME);// 1.5.9版本新加

        // 目前酬金计算暂时没有把宽带预约封顶值计算在内，以后有宽带预约结酬了需要修改计算方式
        Double reward = SalePromotionService.service.getRechargeReward(sale);
        sale.set(SalePromotion.REWARD, reward);// 移植了ApiService中酬金计算的方法

        return sale.save();
    }

}
